/*
 * Copyright (C) 2011-2012 Wojciech Dzierżanowski
 * See LICENSE.txt for licensing details.
 */

package wdzierzan.downstream.android;

import android.util.Log;
import wdzierzan.downstream.core.Streamer;

import java.text.MessageFormat;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

/**
 * Makes <code>java.util.logging</code> logging work with
 * <code>android.util.Log</code>.
 */
class LoggingAdapter {

    private static final String LOG_CORE_TAG = "downstream";

    public static void initLogging() {

        Handler handler = new Handler() {
            @Override
            public void publish(LogRecord logRecord) {
                String tag = LOG_CORE_TAG + ':' + logRecord.getSourceClassName() + '.' + logRecord.getSourceMethodName();
                String message = logRecord.getParameters() == null
                        ? logRecord.getMessage()
                        : MessageFormat.format(logRecord.getMessage(), logRecord.getParameters());

                if (logRecord.getLevel().intValue() <= Level.FINER.intValue())
                    Log.v(tag, message, logRecord.getThrown());
                else if (logRecord.getLevel().intValue() <= Level.FINE.intValue())
                    Log.d(tag, message, logRecord.getThrown());
                else if (logRecord.getLevel().intValue() <= Level.INFO.intValue())
                    Log.i(tag, message, logRecord.getThrown());
                else if (logRecord.getLevel().intValue() <= Level.WARNING.intValue())
                    Log.w(tag, message, logRecord.getThrown());
                else
                    Log.e(tag, message, logRecord.getThrown());
            }
            @Override
            public void flush() {
            }
            @Override
            public void close() throws SecurityException {
            }
        };

        Logger[] loggers = {
                Logger.getLogger(Streamer.class.getPackage().getName()),
                Logger.getLogger(LoggingAdapter.class.getPackage().getName()),
                Logger.getLogger(ch.ethz.ssh2.Connection.class.getPackage().getName()),
        };
        for (Logger logger: loggers) {
            for (Handler h: logger.getHandlers())
                logger.removeHandler(h);
            logger.addHandler(handler);
            logger.setUseParentHandlers(false);
        }

        int[] androidLevels = {Log.VERBOSE, Log.DEBUG, Log.INFO, Log.WARN, Log.ERROR};
        Level[] javaLevels = {Level.FINEST, Level.FINE, Level.INFO, Level.WARNING, Level.SEVERE};
        for (int i = 0; i < androidLevels.length; i++)
            if (Log.isLoggable(LOG_CORE_TAG, androidLevels[i])) {
                for (Logger logger: loggers)
                    logger.setLevel(javaLevels[i]);
                handler.setLevel(javaLevels[i]);
                break;
            }
    }
}
